<template>
  <div class="edit-menu">
    <a-modal
      width="800px"
      :title="updateTitles"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="spinning" tip="正在加载数据中...">
        <a-form :form="form">
          <a-row :gutter="10">
            <a-col :span="12">
              <a-form-item label="上级部门" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-tree-select
                  v-decorator="['PID', { rules: [{ required: true, message: '请选择上级部门!', whitespace: true, trigger: 'change' }] }]"
                  allowClear
                  show-search
                  treeNodeFilterProp="title"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="parentTreeList"
                  placeholder="请选择上级部门"
                  searchPlaceholder="输入部门名称进行筛选"
                  @change="changeParentDepartment"
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <!-- fix: 修改时部门名称不能修改 -->
            <a-col :span="12">
              <a-form-item hasFeedback label="部门名称" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="['DeptName', {
                    rules: [
                      { required: true, message: '', whitespace: true, trigger: 'change' },
                      { validator: validateDeptName }
                    ]
                  }]"
                  :disabled="isDisabled"
                  autocomplete="off"
                  placeholder="请输入部门名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门类型" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-select
                  v-decorator="['DeptLevel', { rules: [{ required: true, message: '请输入部门类型!', whitespace: true, trigger: 'change' }] }]"
                  placeholder="请选择部门类型"
                >
                  <a-select-option v-for="item in categoryList" :key="item.DropID" :value="item.DROPVALUE">{{ item.DROPVALUE }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门地址" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="['DeptAddress']"
                  allowClear
                  autocomplete="off"
                  placeholder="请输入部门地址" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门电话" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="['DeptPhone', {
                    rules: [
                      { required: false, message: '', whitespace: true, trigger: 'change' },
                      { validator: validateFixedTelephone }
                    ]
                  }]"
                  allowClear
                  autocomplete="off"
                  placeholder="请输入部门电话" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="负责人姓名" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input v-decorator="['DeptLeader']" allowClear placeholder="请输入负责人姓名" autocomplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="负责人联系电话" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="['DeptLeadPhone', {
                    rules: [
                      { required: false, message: '', whitespace: true, trigger: 'change' },
                      { validator: validateTelephone}
                    ]
                  }]"
                  allowClear
                  autocomplete="off"
                  placeholder="请输入负责人联系电话" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否政府" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-switch
                  v-decorator="['DeptNO',{
                    valuePropName:'checked'
                  }]" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="10">
            <a-col :span="24">
              <a-form-item label="备注" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                <a-textarea v-decorator="['DeptRemark']" allowClear :auto-size="{ minRows: 3, maxRows: 5 }" placeholder="请输入备注" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import debounce from 'lodash.debounce'
import pick from 'lodash.pick'
import { getTreeList, getDropdownList } from '@/api/common'
import { setDepartments, queryDepartmentNames, getDepartmentInfos } from '@/api/system'
import { validFixedTelphone, validTelphone } from '@/utils/validate'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      confirmLoading: false,
      spinning: false,
      isDisabled: true,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      parentTreeList: [{
        title: '无',
        value: '0',
        key: '0',
        children: []
      }],
      categoryList: [],
      form: this.$form.createForm(this, { name: 'department' })
    }
  },
  watch: {
    'propsData': function () {
      this.fetchDepartment()
    }
  },
  computed: {
    updateTitles: function () {
      const { propsData: { type } } = this
      if (type === 'add') {
        return '新增部门'
      } else if (type === 'addChild') {
        return '新增子部门'
      } else {
        return '修改部门'
      }
    }
  },
  methods: {
    fetchDepartment () {
      this.spinning = true
      const { propsData: { type, id }, form: { setFieldsValue } } = this
      const tree = new Promise((resolve, reject) => {
        getTreeList({ mode: 'dept' }).then(res => {
          resolve(res)
        })
      })
      const category = new Promise((resolve, reject) => {
        getDropdownList({ PmKey: 'bumenleixing' }).then(res => {
          resolve(res)
        })
      })
      const info = new Promise((resolve, reject) => {
        if (type === 'update' && id !== '') {
          getDepartmentInfos({ deptID: id }).then(res => {
            resolve(res)
          })
        } else {
          resolve()
        }
      })
      Promise.all([tree, category, info]).then(res => {
        this.parentTreeList[0].children = res[0]
        this.categoryList = res[1]
        if (type === 'addChild') {
          setFieldsValue({ PID: id })
          this.isDisabled = false
        }
        if (type === 'add' || type === 'addChild') return
        this.isDisabled = false
        const result = res[2].data
        this.$nextTick(() => {
          setFieldsValue(pick(result, ['PID', 'DeptName', 'DeptLevel', 'DeptAddress', 'DeptPhone', 'DeptLeader', 'DeptLeadPhone', 'DeptRemark']))
        })
      }).catch(() => {
        this.$message.error('网络请求失败, 请稍后重试')
      }).finally(() => {
        this.spinning = false
      })
    },
    changeParentDepartment (e) {
      if (e) {
        this.isDisabled = false
      } else {
        this.isDisabled = true
      }
    },
    handleSubmit () {
      const { form: { validateFields }, propsData: { type, id: ID }, $message } = this
      validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          setDepartments({
            State: type === 'update' ? 'update' : 'add',
            sys_department_Modules: Object.assign({}, values, {
              ID,
              CreateTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
              CreateUserID: this.$store.getters.userid,
              CreateUserName: this.$store.getters.name,
              Mode: '0',
              DeptNO: values.DeptNO ? '政府' : ''
            })
          }).then(res => {
            if (res.code === 200) {
              $message.success('提交成功', 3)
              this.handleCancel()
              this.$parent.$parent.$refs.table.refresh(true)
            } else {
              $message.error('提交失败', 3)
            }
          }).catch((err) => {
            $message.error(err, 3)
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.isDisabled = true
      this.$emit('update:visible', false)
    },
    validateDeptName: debounce(function (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入部门名称!'))
      } else {
        const { form: { getFieldValue }, propsData: { type } } = this
        if (type === 'update') {
          callback()
        } else {
          queryDepartmentNames({ DeptName: value, PID: getFieldValue('PID') }).then(res => {
            if (res.code === 201) {
              callback(new Error('当前输入的部门名称已经存在!'))
            } else {
              callback()
            }
          }).catch(() => {
            callback()
          })
        }
      }
    }, 500, { leading: false }),
    validateFixedTelephone (rule, value, callback) {
      if (!value) {
        callback()
      }
      if (!validFixedTelphone(value)) {
        callback(new Error('部门电话输入有误, 请检查后重新输入!'))
      }
      callback()
    },
    validateTelephone (rule, value, callback) {
      if (!value) {
        callback()
      }
      if (!validTelphone(value)) {
        callback(new Error('联系电话输入有误, 请检查后重新输入!'))
      }
      callback()
    }
  }
}
</script>
